const config = require('../util/config')
const logger = require('log4js').getLogger()
const ChromeServerIterator = require('../mng/chromeServerMng').Iterator

module.exports = (req, res) => {
    require('../util/service').handlePost(req, res, (reqObj, resolve) => {
        if (config.domain == '') {
            require('../mng/chromeMng').getCode().then(result => {
                resolve(result)
            })
        } else if (config.domain == 'zoro.site') {
            getFanliCode(new ChromeServerIterator()).then(result => {
                if (result.code && result.codeRequestId)
                    req.session.chromeServer = result.chromeServer
                resolve(result)
            })
        }
    })
}

function getFanliCode(chromeServerIterator) {
    return new Promise(resolve => {
        var chromeServer = chromeServerIterator.next()
        if (!chromeServer) {
            resolve({
                code: '',
                codeRequestId: ''
            })
            return
        }

        require('../util/getHtml')({
            url: chromeServer + 'getFanliCode.do',
            data: '{}'
        }).then(result => {
            // logger.debug('[' + __filename + ':' + __line + ']', result)
            var obj = JSON.parse(result)
            if (obj.code && obj.codeRequestId) {
                obj.chromeServer = chromeServer
                resolve(obj)
            }
            else {
                getFanliCode(chromeServerIterator).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }
        }, result => {
            logger.error('[' + __filename + ':' + __line + ']', result)
            getFanliCode(chromeServerIterator).then(result => {
                resolve(result)
            }, result => {
                reject(result)
            })
        })
    })
}
